# -*- coding:UTF-8 -*-
"""
@Project:   DataCrawler
@FileName:  redis_db.py
@CreateDate:2023/4/24 19:59  
@Author:    Jia  
@Desc:  redis缓存数据库的连接，创建，使用
"""
import redis
import subprocess


def redis_start():
    """
    开启redis服务
    :return code 执行结果代码
    """
    cmd = r'd:;cd D:\ProgramFiles\Redis;redis-server --service-start'
    res = subprocess.run(cmd, shell=True, capture_output=True, encoding='utf-8')
    code = res.returncode

    # print('res.stdout:', res.stdout)
    # print('res.returncode:', res.returncode)
    return code


def redis_conn(logger):
    """
    建立redis连接池, decode_response=True将byte转为字符输出
    :return rds
    """
    code = redis_start()
    if code == 0:
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0, decode_responses=True, max_connections=100)
        logger.info('redis 服务已开启')
        rds = redis.StrictRedis(connection_pool=pool)
        logger.info('redis db0数据库已连接')
        return rds
    else:
        logger.info('redis 服务未开启')


def redis_conn2(logger):
    """使用redis db1数据库建立连接"""

    code = redis_start()
    if code == 0:
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=1, decode_responses=True, max_connections=100)
        logger.info('redis 服务已开启')
        rds1 = redis.StrictRedis(connection_pool=pool)
        logger.info('redis db1数据库已连接')
        return rds1
    else:
        logger.info('redis 服务未开启')

